package com.shuiyun.jtt.server;

import com.shuiyun.jtt.handler.FrameDecoder;
import com.shuiyun.jtt.handler.JTMessageHandler;
import com.shuiyun.jtt.handler.MessageCodecHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author shuiyun
 * @description 客户端服务
 * @date 2022-04-16 16:57
 */
@Slf4j
@Service
public class ClientServer {

    private final static LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    private final static byte[] DELIMITER = new byte[]{0x7e};
    private final MessageCodecHandler messageCodecHandler;
    private final JTMessageHandler jtMessageHandler;

    @Getter
    private Channel channel;

    public ClientServer(MessageCodecHandler messageCodecHandler, JTMessageHandler jtMessageHandler) {
        this.messageCodecHandler = messageCodecHandler;
        this.jtMessageHandler = jtMessageHandler;
    }

    /**
     * 网关服务 随项目自动启动
     *
     * @author shuiyun
     * @date 2022/4/16
     */
    @PostConstruct
    public void start() throws Exception {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(worker);
        bootstrap.option(NioChannelOption.SO_REUSEADDR, true)
                .option(NioChannelOption.TCP_NODELAY, true)
                .option(NioChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new FrameDecoder())
                                .addLast(messageCodecHandler)
                                .addLast(jtMessageHandler);
                    }
                });
        this.channel = bootstrap.connect("127.0.0.1", 8023).sync().channel();
        log.info("连接server服务端 ip：{} port:{}", "127.0.0.1", 8023);
        channel.closeFuture().addListener((ChannelFutureListener) future -> {
            worker.shutdownGracefully();
        });
    }
}
